package com.example.onlinemonitoring.controller;

import com.alibaba.fastjson.JSONObject;
import com.example.onlinemonitoring.Util.tem.SensorAbstractBaseService;
import com.example.onlinemonitoring.dao.*;
import com.example.onlinemonitoring.model.*;
import com.example.onlinemonitoring.model.common.MyResult;
import com.example.onlinemonitoring.model.common.alarmmessage;
import com.example.onlinemonitoring.model.common.deviceinfo;
import com.example.onlinemonitoring.model.common.sensor;
import com.example.onlinemonitoring.serviceImpl.*;
import com.example.onlinemonitoring.Util.LanguageManager;
import ch.qos.logback.core.joran.util.beans.BeanUtil;
import io.swagger.annotations.Api;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import tk.mybatis.mapper.entity.Example;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Api(value = "首页接口", tags = { "首页接口" })
@RestController
@RequestMapping("/index")
public class indexController {
    @Autowired
    AppdeviceServiceImpl appdeviceImpl;
    @Autowired
    AppstationServiceImpl appstationserviceimpl;
    @Autowired
    BeanFactory beanFactory;
    @Autowired
    LanguageManager languageManager;

    @ResponseBody
    @GetMapping("/selectappstation")
    public MyResult<Appstation> selectappstation() {
        return appstationserviceimpl.getList();
    }

    /**
     * Float判空置0
     * 
     * @param value
     * @return
     * @throws ParseException
     */
    public static Float isnull(Float value) {
        if (value == null)
            return 0f;
        else
            return value;
    }

    @ResponseBody
    @RequestMapping(value = "/updateappstation", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    public MyResult<Integer> updateappstation(@RequestBody String jsonParam) {
        JSONObject object = JSONObject.parseObject(jsonParam);
        Appstation record = object.toJavaObject(Appstation.class);
        record.setId(1);
        MyResult<Integer> m = new MyResult<Integer>();
        if (appstationserviceimpl.Update(record, true) >= 1) {
            m.setMsg("修改成功");
            m.setCode(0);
            if (record.getLanguage() != null) {
                languageManager.myInit((record.getLanguage()));
                languageManager.changeDeviceLanguage();
            }
        } else {
            m.setMsg("修改失败");
            m.setCode(1);
        }
        return m;
    }

    @ResponseBody
    @GetMapping("/updateStarttime")
    public MyResult<Integer> updateStarttime(@RequestParam(value = "starttime", required = true) Integer starttime) {
        MyResult<Integer> result = new MyResult<Integer>();
        List<Integer> list = new ArrayList<Integer>();
        Appstation as = new Appstation();
        as.setId(1);
        as = appstationserviceimpl.selectByPrimaryKey(as);
        if (as == null) {
            result.setCode(1);
            result.setMsg("数据库中无总站记录！");
            return result;
        }
        if (as.getStarttime() != null) {
            result.setCode(1);
            result.setMsg("已设置开始时间，请勿重复设置！");
            return result;
        }
        as.setStarttime(starttime);
        appstationserviceimpl.Update(as, true);

        result.setCode(0);
        result.setMsg("设置成功");
        return result;
    }

    @ResponseBody
    @GetMapping("/updateContract")
    public boolean updateContract(@RequestParam(value = "contract", required = true) String contract) {
        Appstation as = new Appstation();
        as.setId(1);
        as.setContract(contract);
        appstationserviceimpl.Update(as, true);
        return true;
    }

    @ResponseBody
    @GetMapping("/isExpired")
    public MyResult<Long> isExpired() {
        MyResult<Long> result = new MyResult<Long>();
        List<Long> list = new ArrayList<Long>();
        Appstation as = new Appstation();
        as.setId(1);
        as = appstationserviceimpl.getModel(as);
        if (as == null) {
            result.setCode(1);
            result.setMsg("数据库中无总站记录！");
            return result;
        }
        if (as.getStarttime() == null) {
            result.setCode(1);
            result.setMsg("管理员未设置开始时间！");
            return result;
        }
        Long nowtimestamp = new Date().getTime();
        Long time = 730l - (nowtimestamp - as.getStarttime() * 1000l) / 86400000l;

        list.add(time);
        list.add(as.getChannelnum().longValue());
        if (list.size() != 0) {
            result.setCode(0);
            result.setMsg("success");
            result.setCount(list.size());
            result.setData(list);
        } else {
            result.setCode(1);
            result.setMsg("数据为空");
        }
        return result;
    }

    @ResponseBody
    @GetMapping("/selectCount")
    public MyResult<rescount> selectCount(@RequestParam(value = "id", required = false) Integer id) {
        Integer totalcount = 0, alarmcount = 0, warncount = 0, normalcount = 0, abnormalcount = 0;
        List<Appdevice> devicelist = new ArrayList<>();
        Example example = new Example(Appdevice.class);
        Example.Criteria criteria = example.createCriteria();
        MyResult<rescount> result = new MyResult<rescount>();
        if (id != null) {
            criteria.andEqualTo("id", id);
            criteria.andEqualTo("isshow", 1);
            // criteria.andEqualTo("installed",1);
            criteria.andNotEqualTo("type", "转发");
            devicelist = appdeviceImpl.getList(example).getData();
        } else {
            criteria.andEqualTo("isshow", 1);
            // criteria.andEqualTo("installed",1);
            devicelist = appdeviceImpl.getList(example).getData();
        }
        if (devicelist == null) {
            result.setCode(1);
            result.setMsg("数据为空");
            return result;
        }
        for (int j = 0; j < devicelist.size(); j++) {
            if (devicelist.get(j).getSensor() != null && !devicelist.get(j).getSensor().equals("")) {
                int stationid = devicelist.get(j).getStationid();
                int devicegroup = devicelist.get(j).getDevicegroup();
                try {
                    SensorAbstractBaseService<sensor, sensor> service = (SensorAbstractBaseService<sensor, sensor>) beanFactory
                            .getBean(devicelist.get(j).getSimple() + "ServiceImpl");
                    totalcount += service.getTotalCount(stationid, devicegroup);
                    alarmcount += service.getAlarmCount(stationid, devicegroup);
                    warncount += service.getWarnCount(stationid, devicegroup);
                    normalcount += service.getNormalCount(stationid, devicegroup);
                    abnormalcount += service.getAbnormalCount(stationid, devicegroup);
                } catch (Exception e) {
                    // TODO: handle exception
                }
            }
        }

        List<rescount> list = new ArrayList<rescount>();
        list.add(new rescount(totalcount, alarmcount, warncount, normalcount, abnormalcount));
        if (list.size() != 0) {
            result.setCode(0);
            result.setMsg("success");
            result.setCount(list.size());
            result.setData(list);
        } else {
            result.setCode(1);
            result.setMsg("数据为空");
        }
        return result;
    }

    @ResponseBody
    @GetMapping("/selectAlarmDevice")
    public MyResult<AppdeviceMobile> selectAlarmDevice() throws ParseException {
        MyResult<AppdeviceMobile> result = new MyResult<AppdeviceMobile>();
        List<Appdevice> devicelists = new ArrayList<Appdevice>();
        Example example = new Example(Appdevice.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("isshow", 1);
        criteria.andNotEqualTo("type", "转发");
        if (appdeviceImpl.getList(example).getData() != null) {
            devicelists = appdeviceImpl.getList(example).getData();
        }

        List<AppdeviceMobile> alarmdevicelists = new ArrayList<AppdeviceMobile>();
        for (Appdevice appdevice : devicelists) {
            if (appdevice.getInstalled() == 1 && !appdevice.getSimple().contains("61850")
                    && !appdevice.getType().equals("转发")) {
                try {
                    SensorAbstractBaseService<sensor, sensor> service = (SensorAbstractBaseService<sensor, sensor>) beanFactory
                            .getBean(appdevice.getSimple() + "ServiceImpl");
                    int count = service.getAlarmCount(appdevice);
                    if (count > 0) {
                        AppdeviceMobile adm = new AppdeviceMobile();
                        BeanUtils.copyProperties(appdevice, adm);
                        adm.setAlarmcount(count);
                        alarmdevicelists.add(adm);
                    }
                } catch (Exception e) {
                    // TODO: handle exception
                }
            }
        }
        if (alarmdevicelists.size() != 0) {
            result.setCode(0);
            result.setMsg("success");
            result.setCount(alarmdevicelists.size());
            result.setData(alarmdevicelists);
        } else {
            result.setCode(1);
            result.setMsg("数据为空");
        }
        return result;
    }

    @ResponseBody
    @GetMapping("/selectAlarm")
    public MyResult<alarmmessage> selectalarm(@RequestParam(value = "id", required = false) Integer id)
            throws ParseException {
        MyResult<alarmmessage> result = new MyResult<alarmmessage>();
        List<alarmmessage> list = new ArrayList<>();
        List<Appdevice> devicelists = new ArrayList<Appdevice>();
        if (id == null) {
            Example example = new Example(Appdevice.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("isshow", 1);
            criteria.andNotEqualTo("type", "转发");
            if (appdeviceImpl.getList(example).getData() != null) {
                devicelists = appdeviceImpl.getList(example).getData();
            }
        } else {
            Appdevice appdevice = new Appdevice();
            appdevice.setId(id);
            Appdevice appdevice1 = appdeviceImpl.selectByPrimaryKey(appdevice);
            if (appdevice1 != null) {
                devicelists.add(appdevice1);
            }
        }
        for (Appdevice appdevice : devicelists) {
            if (appdevice.getInstalled() == 1 && !appdevice.getSimple().contains("61850")
                    && !appdevice.getType().equals("转发")) {
                try {
                    SensorAbstractBaseService<sensor, sensor> service = (SensorAbstractBaseService<sensor, sensor>) beanFactory
                            .getBean(appdevice.getSimple() + "ServiceImpl");
                    list.addAll(service.getAlarmmessageList(appdevice));
                } catch (Exception e) {
                    // TODO: handle exception
                }
            }
        }
        if (list.size() != 0) {
            result.setCode(0);
            result.setMsg("success");
            result.setCount(list.size());
            result.setData(list);
        } else {
            result.setCode(1);
            result.setMsg("数据为空");
        }
        return result;
    }

    @ResponseBody
    @GetMapping("/selectDevice")
    public MyResult<deviceinfo> selectDevice(@RequestParam(value = "isshow", required = false) Integer isshow) {
        MyResult<deviceinfo> result = new MyResult<deviceinfo>();
        Integer totalcount = 0, alarmcount = 0, normalcount = 0, warncount = 0, abnormalcount = 0;
        List<deviceinfo> list = new ArrayList<>();
        List<Appdevice> devicelist = new ArrayList<>();
        if (isshow == null) {
            Example example = new Example(Appdevice.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andNotEqualTo("type", "转发");
            example.orderBy("ordernum").asc();
            devicelist = appdeviceImpl.getList(example).getData();
        } else {
            Example example = new Example(Appdevice.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("isshow", isshow);
            criteria.andNotEqualTo("type", "转发");
            example.orderBy("ordernum").asc();
            devicelist = appdeviceImpl.getList(example).getData();
            if (devicelist == null) {
                int i = 0;
            }
        }

        for (int j = 0; j < devicelist.size(); j++) {
            int stationid = devicelist.get(j).getStationid();
            int devicegroup = devicelist.get(j).getDevicegroup();
            totalcount = 0;
            alarmcount = 0;
            warncount = 0;
            normalcount = 0;
            abnormalcount = 0;
            if (!devicelist.get(j).getSimple().contains("61850") && !devicelist.get(j).getType().equals("转发")) {
                try {
                    SensorAbstractBaseService<sensor, sensor> service = (SensorAbstractBaseService<sensor, sensor>) beanFactory
                            .getBean(devicelist.get(j).getSimple() + "ServiceImpl");
                    totalcount += service.getTotalCount(stationid, devicegroup);
                    alarmcount += service.getAlarmCount(stationid, devicegroup);
                    warncount += service.getWarnCount(stationid, devicegroup);
                    normalcount += service.getNormalCount(stationid, devicegroup);
                    abnormalcount += service.getAbnormalCount(stationid, devicegroup);

                } catch (Exception e) {
                    // TODO: handle exception
                }
            }
            deviceinfo device = new deviceinfo(
                    devicelist.get(j).getId(),
                    devicelist.get(j).getName(),
                    devicelist.get(j).getcSimple(),
                    devicelist.get(j).getEname(),
                    devicelist.get(j).getInstalled(),
                    totalcount, alarmcount + warncount, warncount, normalcount, abnormalcount,
                    devicelist.get(j).getImg());
            list.add(device);
        }
        if (list.size() != 0) {
            result.setCode(0);
            result.setMsg("success");
            result.setCount(list.size());
            result.setData(list);
        } else {
            result.setCode(1);
            result.setMsg("数据为空");
        }
        return result;
    }

    public class rescount {
        public rescount(int totalcount, int alarmcount, int warncount, int normalcount, int abnormalcount) {
            this.totalcount = totalcount;
            this.alarmcount = alarmcount;
            this.warncount = warncount;
            this.normalcount = normalcount;
            this.abnormalcount = abnormalcount;
        }

        int totalcount;
        int alarmcount;
        int warncount;
        int normalcount;
        int abnormalcount;

        public int getTotalcount() {
            return totalcount;
        }

        public void setTotalcount(int totalcount) {
            this.totalcount = totalcount;
        }

        public int getAlarmcount() {
            return alarmcount;
        }

        public void setAlarmcount(int alarmcount) {
            this.alarmcount = alarmcount;
        }

        public int getWarncount() {
            return warncount;
        }

        public void setWarncount(int warncount) {
            this.warncount = warncount;
        }

        public int getNormalcount() {
            return normalcount;
        }

        public void setNormalcount(int normalcount) {
            this.normalcount = normalcount;
        }

        public int getAbnormalcount() {
            return abnormalcount;
        }

        public void setAbnormalcount(int abnormalcount) {
            this.abnormalcount = abnormalcount;
        }
    }

}
